package com.ykun.mq.topics;

import java.io.IOException;

import com.rabbitmq.client.AMQP.BasicProperties;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Consumer;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;
import com.rabbitmq.client.QueueingConsumer;

/**
 * @author yangkun
 * @date 2017年5月8日 下午3:12:02
 * @description
 */
public class ReceiveTopicFortopic {

	private final static String HOST = "127.0.0.1";
	private static final String EXCHANGE_NAME = "topic_Exc";
	private static final String QUEUE = "temp_topic";
	private static final String ROUTKEY = "*_topic";
	private static final boolean durable = true;

	public static void main(String[] argv) throws Exception {
		// 创建连接和频道
		ConnectionFactory factory = new ConnectionFactory();
		factory.setHost(HOST);
		Connection connection = factory.newConnection();
		final Channel channel = connection.createChannel();
		// 声明转发器
		channel.exchangeDeclare(EXCHANGE_NAME, "topic", durable);
		// 持久化
		channel.queueDeclare(QUEUE, durable, false, false, null);
		channel.basicQos(1);
		// 将消息队列绑定到Exchange
		channel.queueBind(QUEUE, EXCHANGE_NAME, ROUTKEY);

		System.out.println(" [*] Waiting for critical messages. To exit press CTRL+C");
		
		Consumer consumer = new DefaultConsumer(channel){
			@Override
			public void handleDelivery(String consumerTag, Envelope envelope, BasicProperties properties, byte[] body)
					throws IOException {
				try {
					String message = new String(body, "utf-8");
					System.out.println(" [x] Received '" + envelope.getRoutingKey() + "':'" + message + "'");
				} catch (Exception e) {
					System.out.println(" [x] Done");
					channel.basicAck(envelope.getDeliveryTag(), false);
				}
			}
		};
		channel.basicConsume(QUEUE, false, consumer);
		
		
		/*QueueingConsumer consumer = new QueueingConsumer(channel);    
        channel.basicConsume(QUEUE, true, consumer);    
    
        while (true)    
        {    
            QueueingConsumer.Delivery delivery = consumer.nextDelivery();    
            String message = new String(delivery.getBody());    
            String routingKey = delivery.getEnvelope().getRoutingKey();    
    
            System.out.println(" [x] Received routingKey = " + routingKey    
                    + ",msg = " + message + ".");    
        }*/
	}

}
